package com.ke.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ke.dao.ArticleMapper;
import com.ke.dao.UserRepository;
import com.ke.dao.VideoMapper;
import com.ke.pojo.Article;
import com.ke.pojo.BaseResp;
import com.ke.pojo.User;
import com.ke.pojo.Video;
import com.ke.service.UserService;
import com.ke.utils.JwtUtils;
import com.ke.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author bochen
 */
@Service
public class UserServiceImpl implements UserService {
    private final UserRepository userRepository;
    private final JavaMailSender javaMailSender;
    private final StringRedisTemplate stringRedisTemplate;
    public UserServiceImpl(UserRepository userRepository,JavaMailSender javaMailSender,StringRedisTemplate stringRedisTemplate){
        this.userRepository=userRepository;
        this.javaMailSender=javaMailSender;
        this.stringRedisTemplate=stringRedisTemplate;
    }

    @Autowired
    JwtUtils jwtUtils;

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    VideoMapper videoMapper;

    @Override
    public BaseResp validateUsername(String username) {
        User user=userRepository.findByUsername(username);
        if (user!=null){
            return new BaseResp(1,"用户名重复");
        }
        return new BaseResp(0,"用户名可用");
    }

    @Override
    public BaseResp validateEmail(String email) {
        User user=userRepository.findByEmail(email);
        if (user!=null){
            return new BaseResp(1,"邮箱已被使用");
        }
        return new BaseResp(0,"邮箱可以使用");
    }

    @Override
    public BaseResp sendMail(String email) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setSubject("验证码");
        simpleMailMessage.setTo(email);
        Random random = new Random();
        StringBuilder stringBuilder = new StringBuilder();
        int codeLength=6;
        for (int i=0;i<codeLength;i++){
            stringBuilder.append(random.nextInt(10));
        }
        simpleMailMessage.setText("验证码是"+stringBuilder.toString());
        javaMailSender.send(simpleMailMessage);
        stringRedisTemplate.opsForValue().set(email,stringBuilder.toString());
        return new BaseResp(0,"发送成功,请去邮箱查看");
    }

    @Override
    public BaseResp registry(User user) {
        String code = stringRedisTemplate.opsForValue().get(user.getEmail());
        if (code!=null&&!user.getCode().equals(code)){
            return new BaseResp(1,"验证码错误");
        }else if(code==null){
            return new BaseResp(2,"请点击获取验证码");
        }
        user.setPassword(MD5Utils.getMD5(user.getPassword(),1,"ke"));
        userRepository.saveAndFlush(user);
        return new BaseResp(0,"注册成功");
    }

    @Override
    public BaseResp login(User user) {
        User byUsername = userRepository.findByUsername(user.getUsername());
        if (byUsername==null){
            return new BaseResp(1,"没有该用户");
        }
        user.setPassword(MD5Utils.getMD5(user.getPassword(),1,"ke"));
        if (!user.getPassword().equals(byUsername.getPassword())){
            return new BaseResp(2,"密码错误");
        }
        //引入jwt生成token
        Map<String, String> map=new HashMap();
        map.put("username",user.getUsername());
        map.put("id",byUsername.getId().toString());
        String token = jwtUtils.createToken(map);
        return new BaseResp(0,"登陆成功",token);
    }

    @Override
    public BaseResp findUser(String username) {
        User byUsername = userRepository.findByUsername(username);
        byUsername.setPassword("*********");
        String s = JSONObject.toJSONString(byUsername);
        return new BaseResp(0,"查询成功",s);
    }

    @Override
    public BaseResp updateUser(Integer id) {
        Optional<User> user1 = userRepository.findById(id);
        User user = user1.get();
        user.setPassword(MD5Utils.getMD5(user.getPassword(),1,"ke"));
        userRepository.saveAndFlush(user);
        return new BaseResp(0,"修改成功");
    }

    /**
     * 模糊查询
     * @param word
     * @return
     */
    @Override
    public BaseResp look(String word) {
        //通过关键词查询文章
        word="%"+word+"%";
        List<Article> artList = articleMapper.findArticleByLike(word);
        //System.out.println(word);
        Map map = new HashMap();
        map.put("arts",artList);

        //通过关键词查询视频
        List<Video> vidList = videoMapper.findVideoByLike(word);
        map.put("vids",vidList);
        //System.out.println(map);
        return new BaseResp(0,"成功",map);
    }

    @Override
    public BaseResp findUserById(Integer id) {
        Optional<User> byId = userRepository.findById(id);
        System.out.println(byId.get());
        if(byId!=null){
            return new BaseResp(0,"查询成功",byId.get());
        }else{
            return new BaseResp(1,"查询失败");
        }
    }
}
